package com.yimin.controller;

import cn.hutool.core.lang.Snowflake;
import com.yimin.Utils.MyHttpRequest;
import com.yimin.databaseS.DatabaseEntity;
import com.yimin.databaseS.DatabaseTableFieldEntity;
import com.yimin.jpa.databaseS.ComDatabaseFieldServerApi;
import com.yimin.jpa.databaseS.ComDatabaseServerApi;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.List;

/**
 * 这是数据库 相关 api Controller
 *
 */
@RestController
@RequestMapping("database")
public class ComProjectDatabaseApiController {


    @Resource
    Snowflake snowflake;


    @Resource
    ComDatabaseServerApi comDatabaseServerApi;


    @Resource
    ComDatabaseFieldServerApi comDatabaseFieldServerApi;

    @PostMapping("addTable")
    public MyHttpRequest adTable(@RequestBody DatabaseEntity databaseEntity){


        databaseEntity.setId(snowflake.nextId()+"");
        comDatabaseServerApi.save(databaseEntity);

       return new MyHttpRequest("成功",200,null);
    }


    @PostMapping("addTableField")
    public MyHttpRequest adTableField(@RequestBody DatabaseTableFieldEntity databaseTableFieldEntity){


        databaseTableFieldEntity.setId(snowflake.nextId()+"");
        comDatabaseFieldServerApi.save(databaseTableFieldEntity);

        return new MyHttpRequest("成功",200,null);
    }


    /**
     * 获取所有表信息
     * @param projectId
     * @return
     */
    @GetMapping("getAll")
    public MyHttpRequest list(@RequestParam String projectId){


        List<DatabaseEntity> re=comDatabaseServerApi.findAllByProjectId(projectId);

        re.forEach(item->{

             item.setFieldNumber(comDatabaseFieldServerApi.findAllByTableId(item.getId()).size());

        });


       return new MyHttpRequest("成功",200,comDatabaseServerApi.findAllByProjectId(projectId));

    }



    @GetMapping("deleteField")
    public MyHttpRequest deleteField(@RequestParam String fieldId){

        DatabaseTableFieldEntity databaseTableFieldEntity1=comDatabaseFieldServerApi.getById(fieldId);

        comDatabaseFieldServerApi.delete(databaseTableFieldEntity1);


        return new MyHttpRequest("删除成功",200,null);
    }


    @GetMapping("deleteTable")
    public MyHttpRequest deleteTable(@RequestParam String tableId){

        DatabaseEntity databaseEntity=comDatabaseServerApi.getById(tableId);

        comDatabaseServerApi.delete(databaseEntity);

        return new MyHttpRequest("删除成功",200,null);

    }


    /**
     * 获取某个表的所有字段信息
     * @param tableId
     * @return
     */
    @GetMapping("getAllfield")
    public MyHttpRequest listfield(@RequestParam String tableId){

           List<DatabaseTableFieldEntity> re=comDatabaseFieldServerApi.findAllByTableId(tableId);

           return new MyHttpRequest("message",200,re);
    }

}
